import { data, directive } from '../ee-directive'
import { popupInstance, loadingOption, loading, fixLoadingOption } from '../popup/popup'

/** binding.modifiers
 * @typedef {object} modifiers
 */

/** el.__loading
 * @typedef {object} loadingdata
 * @property {popupInstance} loading
 * @property {loadingOption} option
 */

// 以下注释可以忽略
/** binding
 * @typedef {object} binding
 * @property {loadingOption | boolean} value
 * @property {string | string[]} [arg] - 没有可以删掉
 * @property {modifiers} modifiers - 没有可以删掉
 */
/** el
 * @typedef {HTMLElement | {__loading: data | loadingdata}} el
 */

export default directive({
  name: 'loading',
  /**
   * @param {el} el
   * @param {binding} binding
   */
  delete(el, binding, vnode, prevVnode) {
    el.__loading.loading?.close();
  },
  /**
   * @param {el} el
   * @param {binding} binding
   */
  init(el, binding, vnode, prevVnode) {
    const data = el.__loading;
    data.option = fixLoadingOption(binding.value);
    if (!data.option.overlay)
      data.option.overlay = 5;
  },
  /**
   * @param {el} el
   * @param {binding} binding
   */
  change(el, binding, vnode, prevVnode) {
    const data = el.__loading;
    if (data.option.overlay >= 4)
      data.option.teleport = el;
    Object.assign(data.option, fixLoadingOption(binding.value));
    if (data.loading?.instance) {
      Object.assign(data.loading.options, data.option);
    } else {
      if (data.option.modelValue || data.option.wait) {
        data.loading = loading(data.option);
      } else {
        data.loading?.close();
      }
    }
  },
})